package org.example.pglog.controller;

import com.alibaba.fastjson.JSON;
import org.example.pglog.mapper.UserMapper;
import org.example.pglog.pojo.Log;
import org.example.pglog.pojo.User;
import org.example.pglog.service.LogService;
import org.example.pglog.util.BeanCompareStringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Field;

/**
 * @author: 船长
 * @create: 2024-09-01 20:26
 **/
@RestController
public class Test2Controller {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogService logService;

    @PostMapping("/save2")
    public String save(@RequestBody User user){
        int i = userMapper.insert(user);
        return i > 0 ? "success" : "fail";
    }

    @PostMapping("/update2")
    public String update(@RequestBody User user){
        User user1 = userMapper.selectById(user.getId());
        logService.db2(user1, user,new String[]{"name","age","hobby"},new String[]{"名称2","年龄2","爱好2"});
        int i = userMapper.updateById(user);
        return i > 0 ? "success" : "fail";
    }

    @PostMapping("/recovery")
    public String recovery(String id){
        Log byId = logService.getById(id);
        String oldNr = byId.getOldNr();
        String newNr = byId.getNewNr();
        String filedenName = byId.getFiledenName();
        User olduser = JSON.parseObject(oldNr, User.class);
        User newuser = JSON.parseObject(newNr, User.class);
        User user = BeanCompareStringUtil.copyFieldValue(olduser, newuser,filedenName);
//        Field[] fields = User.class.getDeclaredFields();
//        for (Field field : fields) {
//            // 设置字段可访问
//            field.setAccessible(true);
//            // 获取字段名
//            String fieldName = field.getName();
//            // 判断字段名是否等于 filedenName
//            if (fieldName.equals(filedenName)) {
//                try {
//                    // 获取字段的值
//                    Object value = field.get(newuser);
//                    System.out.println("Field name: " + fieldName + ", Value: " + value);
//                    // 将olduer中对应的值设置到newuser中
//                    field.set(olduser, value);
//                } catch (IllegalAccessException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//
//            // 更新 oldUser 数据到数据库
        int i = userMapper.updateById(user);
        return i > 0 ? "success" : "fail";
    }
}
